package org.foreningsgatan.genetics;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class ProgramRunnable<T extends Serializable, S extends Serializable> implements Runnable {
	private Program<T, S> program;
	private SimulationEnvironment<T, S> environment;
	private int millis;
	
	private List<SimulationObserver> observers;
	
	public ProgramRunnable(Program<T, S> program, 
			SimulationEnvironment<T, S> environment, int millis) {
		this.program = program;
		this.environment = environment;
		this.millis = millis;
		this.observers = new ArrayList<SimulationObserver>();
	}
	
	public void addObserver(SimulationObserver so) {
		observers.add(so);
	}
	
	@Override
	public void run() {
		try {
			environment.resetAll();
			program.resetResultSet();
			
			while (environment.simulationActive()) {
				program.rootNode.perform(environment);
				environment.act();
				
				for (SimulationObserver observer: observers) {
					observer.update();
				}
				
				Thread.sleep(millis);
			}
			
			environment.applyResult(program.resultSet);
			System.out.println(program.resultSet);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
